package me
import grails.converters.JSON
import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
import groovy.sql.Sql
import groovy.json.*
import groovy.json.JsonSlurper
import oracle.jdbc.pool.OracleDataSource
import com.microsoft.sqlserver.jdbc.SQLServerDataSource
import net.sourceforge.jtds.jdbcx.JtdsDataSource
import grails.plugins.rest.client.RestBuilder
import org.springframework.util.*
import net.sf.json.JSONArray
import net.sf.json.JSONObject

class ChartController {

	def dataSource

    def getData = {chartFile,p->

        def sql = new Sql(dataSource)
        def chartParam = []
        if (chartFile.id!=null && chartFile.id!="") {
            chartParam = sql.rows("select * from chart_param where chart_id = ?",chartFile.id as Integer)
        }

        def results = [dataset:[dimensions:[],source:[]]]
        def ds
        def ip = chartFile.ip
        def db = chartFile.db
        def port = chartFile.port
        def userName = chartFile.userloginid
        def password = chartFile.userpassword
        def dsType = chartFile.ds_type
        if (dsType=="MySql") {
            ds = new MysqlConnectionPoolDataSource();
            ds.setUser(userName);
            ds.setPassword(password);
            ds.setURL("jdbc:mysql://"+ip+":"+port+"/"+db+"?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8");
        }

        if (dsType=="Oracle") {
            ds = new OracleDataSource();
            ds.setDriverType("thin");
            ds.setNetworkProtocol("tcp");
            ds.setServerName(ip);
            ds.setDatabaseName(db);
            ds.setPortNumber(port as Integer);
            ds.setUser(userName); 
            ds.setPassword(password);
        }

        if (dsType=="SqlServer") {
            ds = new JtdsDataSource();
            ds.setServerName(ip);
            ds.setDatabaseName(db);
            ds.setUser(userName);
            ds.setPassword(password);
        }

        def dSql = new Sql(ds)
        def printColNames = { meta ->
            (1..meta.columnCount).each {
                results.dataset.dimensions.add(meta.getColumnLabel(it))
            }
        }

        def printRow = { row ->
            def hm = [:]
            row.toRowResult().keySet().each{
                hm[it] = row[it]
            }
            //println hm
            results.dataset.source.add(hm)
        }
        
        if (chartParam.size()>0) {
            //println  params.name
            chartParam.each{
                
                if (it.param_type=="string") {
                    if (p[it.param_name]==null) {
                        chartFile.chart_sql = chartFile.chart_sql.replace("\${"+it.param_name+"}","'${it.param_default}'")
                    } else {
                        chartFile.chart_sql = chartFile.chart_sql.replace("\${"+it.param_name+"}","'${p[it.param_name]}'")    
                    }
                    
                }
                if (it.param_type=="number") {
                    if (p[it.param_name]==null) {
                        chartFile.chart_sql = chartFile.chart_sql.replace("\${"+it.param_name+"}","${it.param_default}")
                    } else {
                        chartFile.chart_sql = chartFile.chart_sql.replace("\${"+it.param_name+"}","${p[it.param_name]}")
                    }
                    
                } 

            }
            println  chartFile.chart_sql
        }

        chartFile.chart_sql = chartFile.chart_sql.replace('\$','')
        
        def engine = new groovy.text.SimpleTemplateEngine()
        def binding = [:]
        def template = engine.createTemplate(chartFile.chart_sql).make(binding)
        chartFile.chart_sql = template.toString()
        
        try {
            dSql.eachRow(chartFile.chart_sql, printColNames, printRow)
        } catch (e) {
            results = [success:false,message:e.getMessage()]
            println e.getMessage()
        }
       
        return results
    }
    

    def  rowToColumn = {dataset->
        def newDataset = [
            dimensions:[],
            source:[]
        ]
        def dimensionsObj = [:]
        def sourceObj = [:]
        
        if (dataset.dimensions.size()>=3) {
            newDataset.dimensions.add(dataset.dimensions[0])
            for (def i=0;i<dataset.source.size();i++) {
                def data = dataset.source[i]
                def v = data[dataset.dimensions[2]]
                def d = data[dataset.dimensions[1]]
                def s = data[dataset.dimensions[0]]
                if (dimensionsObj[d]==null) {
                    newDataset.dimensions.add(d)
                    dimensionsObj[d] = true  
                }
                if (sourceObj[s]==null) {
                    sourceObj[s] = [:]
                    sourceObj[s][dataset.dimensions[0]] = s
                    sourceObj[s][d] = v
                } else {
                    sourceObj[s][d] = v
                }
                    
            }
            sourceObj.each{
                newDataset.source.add(it.value)
            }

        } 
        if (dataset.dimensions.size()==2) {
            newDataset.dimensions.add(dataset.dimensions[0])
            for (def i=0;i<dataset.source.size();i++) {
                def data = dataset.source[i]
                def d = data[dataset.dimensions[1]]
                def s = data[dataset.dimensions[0]]
                //console.log(dimensionsObj[d])
                if (dimensionsObj[d]==null) {
                    newDataset.dimensions.add(d)
                    dimensionsObj[d] = true  
                }
                if (sourceObj[s]==null) {
                    sourceObj[s] = [:]
                    sourceObj[s][dataset.dimensions[0]] = s
                    sourceObj[s][d] = null
                } else {
                    sourceObj[s][d] = null
                }
                    
            }
            sourceObj.each{
                newDataset.source.add(it.value)
            }
        }

        if (dataset.dimensions.size()==1) {
            newDataset.dimensions.add(dataset.dimensions[0])
            for (def i=0;i<dataset.source.size();i++) {
                def data = dataset.source[i]
                def v = null
                def s = data[dataset.dimensions[0]]
                
                if (sourceObj[s]==null) {
                    sourceObj[s] = [:]
                    sourceObj[s][dataset.dimensions[0]] = s
                    
                } else {
                    
                }
                    
            }
            sourceObj.each{
                newDataset.source.add(it.value)
            }
        }    

        return newDataset
    }


    def view() {


        def slurper = new JsonSlurper()
        def sql = new Sql(dataSource)
        def chartFile = []



        def cf = Util.cacheChartFile[params.token]
        def time1 = new Date()
        if (cf!=null) {
            def chartDataSource = params._DATASOURCE!=null?params._DATASOURCE:cf.chart_datasource
            def chartTheme = params._THEME!=null?params._THEME:cf.theme_id
            def chartTableTheme = cf.table_theme_id

            if (chartDataSource!=null && chartDataSource!="" && chartDataSource!=-1 && chartDataSource!=-2) {
                cf.userloginid = Util.cacheChartDataSource[chartDataSource+""].userloginid
                cf.ds_type = Util.cacheChartDataSource[chartDataSource+""].ds_type
                cf.userpassword = Util.cacheChartDataSource[chartDataSource+""].userpassword
                cf.port = Util.cacheChartDataSource[chartDataSource+""].port
                cf.name = Util.cacheChartDataSource[chartDataSource+""].name
                cf.ip = Util.cacheChartDataSource[chartDataSource+""].ip
                cf.db = Util.cacheChartDataSource[chartDataSource+""].db
            }

            //println chartTheme!=null && chartTheme!=""
            if (chartTheme!=null && chartTheme!="") {
                cf.themeId = Util.cacheChartTheme[chartTheme+""].id
                cf.theme_name = Util.cacheChartTheme[chartTheme+""].theme_name
                cf.theme_source = Util.cacheChartTheme[chartTheme+""].theme_source
            } else {
                cf.themeId = null
                cf.theme_name = null
                cf.theme_source = null
            }

            if (chartTableTheme!=null && chartTableTheme!="") {
                cf.tableThemeSource = Util.cacheChartTableTheme[chartTableTheme+""].theme_source
            } else {
                cf.tableThemeSource = null
            }





            println cf.tableThemeSource
            chartFile.add(cf)
        }


        def time2 = new Date()

        //println Util.cacheChartParam[cf.id+""]

        //println(chartFile)
        //println(chartFile[0])
        //println(chartFile[0].theme_id)
        def time3
        def time4
        if (chartFile.size()>0) {
            def chartSourceStr = chartFile[0].chart_source as String

            def chartParam = Util.cacheChartParam[cf.id+""]==null?[]:Util.cacheChartParam[cf.id+""]//sql.rows("select * from chart_param where chart_id = ?",chartFile[0].id)
            def form = new LinkedMultiValueMap<String, String>()
            def url = chartFile[0].remote_url?chartFile[0].remote_url:""
            def binding = new Binding();
            chartParam.each{
                if (it.param_type=="string") {
                    if (params[it.param_name]==null) {
                        try {
                            chartSourceStr = chartSourceStr.replace("\${"+it.param_name+"}","${it.param_default}")
                            form.add(it.param_name,it.param_default)
                            url = url.replace("\${"+it.param_name+"}","${it.param_default}")
                            binding.setVariable(it.param_name, it.param_default);
                        } catch(e) {
                            println e
                        }
                    } else {
                        chartSourceStr = chartSourceStr.replace("\${"+it.param_name+"}","${params[it.param_name]}")
                        form.add(it.param_name,params[it.param_name])
                        url = url.replace("\${"+it.param_name+"}","${params[it.param_name]}")
                        binding.setVariable(it.param_name, params[it.param_name]);
                    }

                }
                if (it.param_type=="number") {
                    if (params[it.param_name]==null) {
                        chartSourceStr = chartSourceStr.replace("\${"+it.param_name+"}","${it.param_default}")
                        form.add(it.param_name,it.param_default)
                        url = url.replace("\${"+it.param_name+"}","${it.param_default}")
                        binding.setVariable(it.param_name, it.param_default);
                    } else {
                        chartSourceStr = chartSourceStr.replace("\${"+it.param_name+"}","${params[it.param_name]}")
                        form.add(it.param_name,params[it.param_name])
                        url = url.replace("\${"+it.param_name+"}","${params[it.param_name]}")
                        binding.setVariable(it.param_name, params[it.param_name]);
                    }

                }

            }

            time3 = new Date()

            //def chartSource = slurper.parseText(chartSourceStr)
            def chartSource = JSONObject.fromObject( chartSourceStr );

            if (params.cache==null||params.cache==""||params.cache=="false") {

                if (chartFile[0].chart_datasource!=-1 && chartFile[0].chart_datasource!=-2) {
                    def data = getData(chartFile[0],params)

                    if (chartFile[0].row_mode!=null && chartFile[0].row_mode) {
                        chartSource.dataset = rowToColumn(data.dataset)
                    } else {
                        chartSource.dataset = data.dataset
                    }
                }

                if (chartFile[0].chart_datasource==-2) {
                    def dataset = [:]
                    dataset.dimensions = []
                    dataset.source = []
                    def rest = new RestBuilder()

                    if (chartFile[0].remote_adapter_id==null||chartFile[0].remote_adapter_id=="") {
                        def resp = rest.post(url){
                            accept("application/json")
                            contentType("application/x-www-form-urlencoded")
                            body(form)
                        }

                        resp.json.results.each{
                            if (dataset.dimensions.size()==0) {
                                it.each{
                                    dataset.dimensions.push(it.key)
                                }
                            }
                            dataset.source.add(it)
                        }
                        chartSource.dataset = dataset
                    } else {
                        binding.setVariable("url", url);
                        def remoteAdapters = Util.cacheChartAdapter[chartFile[0].remote_adapter_id+""]

                        try {
                            GroovyShell shell = new GroovyShell(binding);
                            Object value = shell.evaluate(remoteAdapters.adapter_source);
                            println value
                            value.results.each{
                                if (dataset.dimensions.size()==0) {
                                    it.each{
                                        dataset.dimensions.push(it.key)
                                    }
                                }
                                dataset.source.add(it)
                            }
                            chartSource.dataset = dataset
                        } catch (e) {
                            println e
                        }

                    }

                    if (chartFile[0].row_mode!=null && chartFile[0].row_mode) {
                        chartSource.dataset = rowToColumn(chartSource.dataset)
                    }

                }


            }
            time4 = new Date()

            if (params.dynamicSeries!=null&&params.dynamicSeries=="true" || chartFile[0].dynamic_series!=null&&chartFile[0].dynamic_series) {

                def templateSeries = chartSource.series
                def dimensionsSize = chartSource.dataset.dimensions.size()
                def seriesSize = chartSource.series.size()

                chartSource.series = JSONArray.fromObject([]);

                for (int i=0;i<(dimensionsSize-1);i++) {
                    //println chartSource.dataset.dimensions[i+1]
                    def flag = (chartSource.dataset.dimensions[i+1]+"").indexOf('@')
                    //println "end"
                    if (flag==-1) {
                        chartSource.series.add(templateSeries[0])
                    } else {
                        def flagIndex = chartSource.dataset.dimensions[i+1].substring(flag+1)
                        chartSource.series.add(templateSeries[flagIndex as Integer])
                    }

                }

                def newDataset = [dimensions:[],source:[]]
                chartSource.dataset.dimensions.each{
                    if ((it+"").indexOf("@")!=-1) {
                        newDataset.dimensions.add((it+"").substring(0,(it+"").indexOf("@")))
                    } else {
                        newDataset.dimensions.add((it+""))
                    }
                }
                chartSource.dataset.source.each{
                    def hm = [:]
                    it.each{it1->
                        if (it1.key.indexOf("@")!=-1) {
                            hm[it1.key.substring(0,it1.key.indexOf("@"))] = it1.value
                        } else {
                            hm[it1.key] = it1.value
                        }
                    }
                    newDataset.source.add(hm)
                }

                chartSource.dataset = newDataset
                //chartSource.dataset = data.dataset
            }


            def time5 = new Date()
            [time1:time1,time2:time2,time3:time3,time4:time4,time5:time5,chartFile:chartFile[0],chartSource:chartSource.toString()]
        } else {
            [chartFile:[:],chartSource:JsonOutput.toJson([:])]
        }
    }

    def preview() {
       
        def slurper = new JsonSlurper()
        def sql = new Sql(dataSource)
        def chartFile



        if (params._THEME==null) {
            if (params._DATASOURCE==null) {
                chartFile = sql.rows("""select a.*,b.id themeId,b.theme_name,b.theme_source,c.userloginid,
                c.ds_type,c.userpassword,c.port,c.name,c.ip,c.db,d.theme_source tableThemeSource
                from chart_file a
                left join chart_theme b on a.theme_id = b.id
                left join data_source_hy_info c on a.chart_datasource=c.id
                left join table_theme d on d.id= a.table_theme_id
                where a.token=? """,params.token)
            } else {
                chartFile = sql.rows("""select a.*,b.id themeId,b.theme_name,b.theme_source,c.userloginid,
                c.ds_type,c.userpassword,c.port,c.name,c.ip,c.db,d.theme_source tableThemeSource
                from chart_file a
                left join chart_theme b on a.theme_id = b.id
                left join data_source_hy_info c on c.id=${params._DATASOURCE}
                left join table_theme d on d.id= a.table_theme_id
                where a.token=? """,params.token)
            }
            
        } else {
            if (params._DATASOURCE==null) {
                chartFile = sql.rows("""select a.*,b.id themeId,b.theme_name,b.theme_source,c.userloginid,
                c.ds_type,c.userpassword,c.port,c.name,c.ip,c.db,d.theme_source tableThemeSource 
                from chart_file a
                left join chart_theme b on b.id = ${params._THEME}
                left join data_source_hy_info c on a.chart_datasource=c.id
                left join table_theme d on d.id= a.table_theme_id
                where a.token=? """,params.token)
            } else{
                chartFile = sql.rows("""select a.*,b.id themeId,b.theme_name,b.theme_source,c.userloginid,
                c.ds_type,c.userpassword,c.port,c.name,c.ip,c.db,d.theme_source tableThemeSource 
                from chart_file a
                left join chart_theme b on b.id = ${params._THEME}
                left join data_source_hy_info c on c.id=${params._DATASOURCE}
                left join table_theme d on d.id= a.table_theme_id
                where a.token=? """,params.token) 
            }
            
        }




        //println(chartFile)    
        println(chartFile[0])    
        println(chartFile[0].theme_id)

        if (chartFile.size()>0) {
            def chartSourceStr = chartFile[0].chart_source as String
            
            def chartParam = sql.rows("select * from chart_param where chart_id = ?",chartFile[0].id)
            def form = new LinkedMultiValueMap<String, String>()
            def url = chartFile[0].remote_url?chartFile[0].remote_url:""
            def binding = new Binding();
            chartParam.each{
                if (it.param_type=="string") {
                    if (params[it.param_name]==null) {
                        try {
                            chartSourceStr = chartSourceStr.replace("\${"+it.param_name+"}","${it.param_default}")
                            form.add(it.param_name,it.param_default)
                            url = url.replace("\${"+it.param_name+"}","${it.param_default}")
                            binding.setVariable(it.param_name, it.param_default);
                        } catch(e) {
                            println e
                        }
                    } else {
                        chartSourceStr = chartSourceStr.replace("\${"+it.param_name+"}","${params[it.param_name]}")   
                        form.add(it.param_name,params[it.param_name])
                        url = url.replace("\${"+it.param_name+"}","${params[it.param_name]}") 
                        binding.setVariable(it.param_name, params[it.param_name]);
                    }
                    
                }
                if (it.param_type=="number") {
                    if (params[it.param_name]==null) {
                        chartSourceStr = chartSourceStr.replace("\${"+it.param_name+"}","${it.param_default}")
                        form.add(it.param_name,it.param_default)
                        url = url.replace("\${"+it.param_name+"}","${it.param_default}")
                        binding.setVariable(it.param_name, it.param_default);
                    } else {
                        chartSourceStr = chartSourceStr.replace("\${"+it.param_name+"}","${params[it.param_name]}")
                        form.add(it.param_name,params[it.param_name])
                        url = url.replace("\${"+it.param_name+"}","${params[it.param_name]}")
                        binding.setVariable(it.param_name, params[it.param_name]);
                    }
                    
                } 

            }
           

            //def chartSource = slurper.parseText(chartSourceStr)
            def chartSource = JSONObject.fromObject( chartSourceStr );
            
            if (params.cache==null||params.cache==""||params.cache=="false") {

                if (chartFile[0].chart_datasource!=-1 && chartFile[0].chart_datasource!=-2) {
                    def data = getData(chartFile[0],params)

                    if (chartFile[0].row_mode!=null && chartFile[0].row_mode) {
                        chartSource.dataset = rowToColumn(data.dataset)
                    } else {
                        chartSource.dataset = data.dataset
                    }
                } 

                if (chartFile[0].chart_datasource==-2) {
                    def dataset = [:]
    				dataset.dimensions = []
    				dataset.source = []
					def rest = new RestBuilder()
					
					if (chartFile[0].remote_adapter_id==null||chartFile[0].remote_adapter_id=="") {
                        def resp = rest.post(url){
                            accept("application/json")
                            contentType("application/x-www-form-urlencoded")
                            body(form)
                        }

                        resp.json.results.each{
                            if (dataset.dimensions.size()==0) {
                                it.each{
                                    dataset.dimensions.push(it.key)
                                }
                            }
                            dataset.source.add(it)
                        }
                        chartSource.dataset = dataset
                    } else {
                        binding.setVariable("url", url);
                        def remoteAdapters = sql.rows("select * from remote_adapter where id = ?",chartFile[0].remote_adapter_id)
            
                        try {
                            GroovyShell shell = new GroovyShell(binding);
                            Object value = shell.evaluate(remoteAdapters[0].adapter_source);
                            println value
                            value.results.each{
                                if (dataset.dimensions.size()==0) {
                                    it.each{
                                        dataset.dimensions.push(it.key)
                                    }
                                }
                                dataset.source.add(it)
                            }
                            chartSource.dataset = dataset
                        } catch (e) {
                            println e
                        }
		
                    }
                    
                    if (chartFile[0].row_mode!=null && chartFile[0].row_mode) {
                        chartSource.dataset = rowToColumn(chartSource.dataset)
                    } 
					
                }


            }


           
            if (params.dynamicSeries!=null&&params.dynamicSeries=="true" || 
                chartFile[0].dynamic_series!=null&&chartFile[0].dynamic_series) {
               
                def templateSeries = chartSource.series
                def dimensionsSize = chartSource.dataset.dimensions.size()
                def seriesSize = chartSource.series.size()
               
                chartSource.series = JSONArray.fromObject([]);

                println chartSource.dataset.dimensions

                for (int i=0;i<(dimensionsSize-1);i++) {
                    //println chartSource.dataset.dimensions[i+1]
                    def flag = (chartSource.dataset.dimensions[i+1]+"").indexOf('@')
                    //println "end"
                    if (flag==-1) {
                        chartSource.series.add(templateSeries[0])
                    } else {
                        def flagIndex = chartSource.dataset.dimensions[i+1].substring(flag+1)
                        chartSource.series.add(templateSeries[flagIndex as Integer])
                    }
                   
                }    

                def newDataset = [dimensions:[],source:[]]
                chartSource.dataset.dimensions.each{
                    if ((it+"").indexOf("@")!=-1) {
                        newDataset.dimensions.add((it+"").substring(0,(it+"").indexOf("@")))
                    } else {
                        newDataset.dimensions.add((it+""))
                    }
                }
                chartSource.dataset.source.each{
                    def hm = [:]
                    it.each{it1->
                        if (it1.key.indexOf("@")!=-1) {
                            hm[it1.key.substring(0,it1.key.indexOf("@"))] = it1.value
                        } else {
                            hm[it1.key] = it1.value
                        }
                    }
                    newDataset.source.add(hm) 
                }
                        
                chartSource.dataset = newDataset
                //chartSource.dataset = data.dataset
            }

            println 454545
            println chartSource.dataset.dimensions

            [chartFile:chartFile[0],chartSource:chartSource.toString()]
        } else {
            [chartFile:[:],chartSource:JsonOutput.toJson([:])]
        }
    }

    def render() {
        def slurper = new JsonSlurper()
        def results = [success:true]
        def sql = new Sql(dataSource)
        def wid = params.wid
        def wp = params.wp
        if (wp) {
            wp = slurper.parseText(params.wp)
        } else {
            wp = [:]
        }
        def wcache = params.wcache
        def rows = sql.rows("""select a.*,b.theme_name,b.theme_source,c.userloginid,
        c.ds_type,c.userpassword,c.port,c.ip,c.db 
        from chart_file a
        left join chart_theme b on a.theme_id = b.id
        left join data_source_hy_info c on a.chart_datasource=c.id
        where a.token=? """,wid)
      
        if (rows.size()!=0){
            def chartParam = sql.rows("select * from chart_param where chart_id = ?",rows[0].id)
            println rows[0]
            def chartSource = rows[0].chart_source
            def form = new LinkedMultiValueMap<String, String>()
            def url = rows[0].remote_url?rows[0].remote_url:""
            def binding = new Binding();
            chartParam.each{
                
                if (it.param_type=="string") {
                    if (wp[it.param_name]==null) {
                        try {
                            chartSource = chartSource.replace("\${"+it.param_name+"}","${it.param_default}")
                            form.add(it.param_name,it.param_default)
                            url = url.replace("\${"+it.param_name+"}","${it.param_default}")
                            binding.setVariable(it.param_name, it.param_default);
                        } catch(e) {
                            println e
                        }
                    } else {
                        chartSource = chartSource.replace("\${"+it.param_name+"}","${wp[it.param_name]}")  
                        form.add(it.param_name,wp[it.param_name])
                        url = url.replace("\${"+it.param_name+"}","${wp[it.param_name]}")
                        binding.setVariable(it.param_name, wp[it.param_name]);  
                    }
                    
                }
                if (it.param_type=="number") {
                    if (wp[it.param_name]==null) {
                        chartSource = chartSource.replace("\${"+it.param_name+"}","${it.param_default}")
                        form.add(it.param_name,it.param_default)
                        url = url.replace("\${"+it.param_name+"}","${it.param_default}")
                        binding.setVariable(it.param_name, it.param_default);
                    } else {
                        chartSource = chartSource.replace("\${"+it.param_name+"}","${wp[it.param_name]}")
                        form.add(it.param_name,wp[it.param_name])
                        url = url.replace("\${"+it.param_name+"}","${wp[it.param_name]}")
                        binding.setVariable(it.param_name, wp[it.param_name]);  
                    }
                    
                } 

            }

            
            results.themeName = rows[0].theme_name
            results.themeSource = rows[0].theme_source
            if (chartSource!=null&&chartSource!="") {
                //chartSource = slurper.parseText(chartSource) 
                chartSource = chartSource.replace("null","\"null\"")
                
                chartSource = JSONObject.fromObject(chartSource); 
               
                if (wcache==null||wcache==""||wcache=="false") {

                    if (rows[0].chart_datasource!=-1 && rows[0].chart_datasource!=-2) {
                        def data = getData(rows[0],params)

                        if (rows[0].row_mode!=null && rows[0].row_mode) {
                            chartSource.dataset = rowToColumn(data.dataset)
                        } else {
                            chartSource.dataset = data.dataset
                        }
                    }
                    

                    if (rows[0].chart_datasource==-2) {
                        def dataset = [:]
                        dataset.dimensions = []
                        dataset.source = []
                        def rest = new RestBuilder()
                        
                        if (rows[0].remote_adapter_id==null||rows[0].remote_adapter_id=="") {
                            def resp = rest.post(url){
                                accept("application/json")
                                contentType("application/x-www-form-urlencoded")
                                body(form)
                            }

                            resp.json.results.each{
                                if (dataset.dimensions.size()==0) {
                                    it.each{
                                        dataset.dimensions.push(it.key)
                                    }
                                }
                                dataset.source.add(it)
                            }
                            chartSource.dataset = dataset
                        } else {
                            binding.setVariable("url", url);
            
                            try {
                                GroovyShell shell = new GroovyShell(binding);
                                def remoteAdapters = sql.rows("select * from remote_adapter where id = ?",rows[0].remote_adapter_id)
                                Object value = shell.evaluate(remoteAdapters[0].adapter_source);
                                println value
                                value.results.each{
                                    if (dataset.dimensions.size()==0) {
                                        it.each{
                                            dataset.dimensions.push(it.key)
                                        }
                                    }
                                    dataset.source.add(it)
                                }
                                chartSource.dataset = dataset
                            } catch (e) {
                                println e
                            }
            
                        }
					
                    }
                    

                    if (params.dynamicSeries!=null&&params.dynamicSeries=="true" || 
                        rows[0].dynamic_series!=null&&rows[0].dynamic_series) {
                        def templateSeries = chartSource.series
                        def dimensionsSize = chartSource.dataset.dimensions.size()
                        def seriesSize = chartSource.series.size()

                        chartSource.series = []

                        for (int i=0;i<(dimensionsSize-1);i++) {
                            def flag = chartSource.dataset.dimensions[i+1].indexOf('@')
                            if (flag==-1) {
                                chartSource.series.add(templateSeries[0])
                            } else {
                                def flagIndex = chartSource.dataset.dimensions[i+1].substring(flag+1)
                                chartSource.series.add(templateSeries[flagIndex as Integer])
                            }
                        }    
                        
                        def newDataset = [dataset:[],source:[]]
                        chartSource.dataset.dimensions.each{
                            if (it.indexOf("@")!=-1) {
                                newDataset.dataset.add(it.substring(0,it.indexOf("@"))) 
                            } else {
                                newDataset.dataset.add(it)
                            }
                        }
                        chartSource.dataset.source.each{
                            def hm = [:]
                            it.each{it1->
                                if (it1.key.indexOf("@")!=-1) {
                                    hm[it1.key.substring(0,it1.key.indexOf("@"))] = it1.value
                                } else {
                                    hm[it1.key] = it1.value
                                }
                            }
                            newDataset.source.add(hm) 
                        }
                        
                        chartSource.dataset = newDataset
                    }

                }
                results.chartSource = chartSource.toString()
            } else {
                chartSource = {}
                results.chartSource = chartSource.toString()
            }
        } else {
            results = [success:false]
        }
        //println results
        render "success_callback("+JsonOutput.toJson(results)+")"
    }
   	
}
